import React from 'react';
import { useHistory } from 'react-router-dom'
import s from './style.module.less'
import { createForm } from 'rc-form';
import { NavBar, Cell, Input, Button, Toast } from 'zarm'
import { ArrowLeft } from '@zarm-design/icons';
import { post } from '@/utils'


const cPassword = (props) => {

    const { getFieldProps, getFieldError } = props.form
    const history = useHistory()


    const submit = () => {
        // validateFields  获取表单属性元素
        props.form.validateFields(async (error, value) => {
            // error 表示有错误，反之验证成功
            if (!error) {
                console.log(value);
                // 两次输入密码不同
                if (value.newpass != value.newpass2) {
                    Toast.show('两次输入的新密码不同')
                    return null
                }

                console.log('111111');

                // // 直接发送请求，一次就可以，由后端校验正确性
                const data= await post('/api/user/alterPassword', {
                    old_pass: value.oldpass,
                    new_pass: value.newpass
                })
                console.log(data);
                if (data.code === 500) {
                    // 原密码出错
                    Toast.show('原密码出错')
                    return
                }
                if (data.code === 200) {
                    // 密码修改成功
                    Toast.show('密码修改成功')
                    history.goBack()
                }
            }
        })

    }
    return (
        <div>
            <NavBar
                left={<ArrowLeft theme="primary" onClick={() => window.history.back()} />}
                title="修改密码"
            />
            <div className={s.cpassword}>
                <div className={s.form}>
                    <Cell title="原密码">
                        <Input
                            clearable
                            type="password"
                            placeholder="请输入原密码"
                            {...getFieldProps('oldpass', { rules: [{ required: true }] })}
                        />
                    </Cell>
                    <Cell title="新密码">
                        <Input
                            clearable
                            type="password"
                            placeholder="请输入新密码"
                            {...getFieldProps('newpass', { rules: [{ required: true }] })}
                        />
                    </Cell>
                    <Cell title="确认密码">
                        <Input
                            clearable
                            type="password"
                            placeholder="请再此输入新密码确认"
                            {...getFieldProps('newpass2', { rules: [{ required: true }] })}
                        />
                    </Cell>
                </div>
                <Button className={s.btn} block theme="primary" onClick={submit}>提交</Button>

            </div>
        </div >

    )
}

export default createForm()(cPassword);
